package threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * 连个线程交替打印0~100的奇偶数，用synchronized关键字实现   使用synchronize效率低
 * https://javaweixin6.blog.csdn.net/article/details/108298855
 */
public class WaitNotifyPrintOddEventSyn {

    private volatile static int count;
    private static final Object lock = new Object();

    // 新建2个线程
    // 1个只处理偶数，第二个只处理奇数（用位运算）
    // 用synchronized来通信
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100){
                    synchronized (lock){
                        // 判断奇偶数
                        if ((count & 1) == 0){
                            System.out.println(Thread.currentThread().getName() + " : " + count);
                            count++;
                        }
                    }
                }
            }
        },"偶数").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count < 100){
                    synchronized (lock){
                        // 判断奇偶数
                        if ((count & 1) == 1){
                            System.out.println(Thread.currentThread().getName() + " : " + count);
                            count++;
                        }
                    }
                }
            }
        },"奇数").start();
    }


}
